<template>
    <div class="home-container">
        <el-card v-if="user" v-loading="userLoading">
            <template #header>
                <div class="card-header">
                    <span>个人信息</span>
                </div>
            </template>
            <el-descriptions :column="2" border>
                <el-descriptions-item label="用户ID">{{ user.id }}</el-descriptions-item>
                <el-descriptions-item label="用户名">{{ user.username }}</el-descriptions-item>
                <el-descriptions-item label="真实姓名">{{ user.realName }}</el-descriptions-item>
                <el-descriptions-item label="电子邮件">{{ user.email }}</el-descriptions-item>
                <el-descriptions-item label="性别">{{ user.gender }}</el-descriptions-item>
                <el-descriptions-item label="年龄">{{ user.age }}</el-descriptions-item>
                <el-descriptions-item label="角色" :span="2">
                    <el-tag v-for="role in user.roles" :key="role" style="margin-right: 5px;">
                        {{ role }}
                    </el-tag>
                </el-descriptions-item>
            </el-descriptions>
        </el-card>
        <el-empty v-else description="无法加载用户信息" />

        <el-card class="mt-4" v-loading="accountLoading">
            <template #header>
                <div class="card-header">
                    <span>我的投资账户</span>
                </div>
            </template>
            <div v-if="account">
                <el-descriptions title="账户概览" :column="2" border>
                    <el-descriptions-item label="账户ID (用户ID)">{{ account.userId }}</el-descriptions-item>
                    <el-descriptions-item label="风险等级">
                        <el-tag>{{ account.riskLevel || '未设置' }}</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="账户余额" :span="2">
                        <el-tag type="success" size="large">¥ {{ account.balance.toFixed(2) }}</el-tag>
                    </el-descriptions-item>
                </el-descriptions>

                <div class="holdings-section">
                    <h4 class="holdings-title">我的持仓</h4>
                    <el-table :data="account.holdings" border style="width: 100%" empty-text="暂无持仓记录">
                        <el-table-column prop="fundCode" label="基金代码" width="180"></el-table-column>
                        <el-table-column prop="shares" label="持有份额">
                            <template #default="scope">
                                {{ scope.row.shares.toFixed(4) }}
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <div v-else class="account-placeholder">
                <el-empty description="您尚未开通投资账户">
                    <el-button type="primary" @click="openCreateDialog">立即开通账户</el-button>
                </el-empty>
            </div>
        </el-card>

        <el-dialog v-model="createDialogVisible" title="开通投资账户" width="600px" @closed="resetForm"
            :close-on-click-modal="false">
            <el-steps :active="activeStep" finish-status="success" simple style="margin-bottom: 20px;">
                <el-step title="风险评估" />
                <el-step title="设置资金" />
                <el-step title="确认信息" />
            </el-steps>

            <div v-if="activeStep === 0">
                <el-form :model="kycForm" ref="kycFormRef" label-position="top">
                    <el-form-item label="1. 您的投资经验是？" prop="q1">
                        <el-radio-group v-model="kycForm.q1">
                            <el-radio :label="1">几乎没有</el-radio>
                            <el-radio :label="2">1-3年</el-radio>
                            <el-radio :label="3">3年以上</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="2. 当您的投资组合在一个月内下跌20%，您会怎么做？" prop="q2">
                        <el-radio-group v-model="kycForm.q2">
                            <el-radio :label="1">立即卖出</el-radio>
                            <el-radio :label="2">继续持有并观望</el-radio>
                            <el-radio :label="3">追加投资</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
            </div>

            <div v-if="activeStep === 1">
                <el-form :model="form" ref="balanceFormRef" label-width="100px">
                    <el-form-item label="初始余额" prop="balance">
                        <el-input-number v-model="form.balance" :precision="2" :step="1000" :min="0"
                            controls-position="right" style="width: 100%;"></el-input-number>
                    </el-form-item>
                </el-form>
            </div>

            <div v-if="activeStep === 2">
                <el-descriptions title="请确认您的开户信息" :column="1" border>
                    <el-descriptions-item label="用户ID">{{ user.id }}</el-descriptions-item>
                    <el-descriptions-item label="评估风险等级">
                        <el-tag type="warning" size="large">{{ determinedRiskLevel.name }} ({{ determinedRiskLevel.code
                            }})</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="初始余额">
                        <span style="font-weight: bold; color: #67C23A;">¥ {{ form.balance.toFixed(2) }}</span>
                    </el-descriptions-item>
                </el-descriptions>
            </div>

            <template #footer>
                <el-button @click="prevStep" v-if="activeStep > 0">上一步</el-button>
                <el-button type="primary" @click="nextStep" v-if="activeStep < 2">下一步</el-button>
                <el-button type="primary" @click="handleCreate" v-if="activeStep === 2"
                    :loading="submitting">确认开通</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useAuthStore } from '@/store/auth';
import { getAccountByUserId, createAccount } from '@/api/accountApi';
import { ElMessage } from 'element-plus';

const authStore = useAuthStore();

// State
const user = computed(() => authStore.state.user);
const userLoading = ref(false);

const account = ref(null);
const accountLoading = ref(true);
const submitting = ref(false);
const createDialogVisible = ref(false);

// --- New state for multi-step form ---
const activeStep = ref(0);
const kycFormRef = ref(null);
const kycForm = reactive({ q1: null, q2: null });
const balanceFormRef = ref(null);
const form = reactive({
    userId: null,
    balance: 100000.00,
    riskLevel: null, // Will be determined by KYC
    holdings: []
});

const determinedRiskLevel = computed(() => {
    const score = (kycForm.q1 || 0) + (kycForm.q2 || 0);
    if (score <= 2) return { code: 'R1', name: '谨慎型' };
    if (score === 3) return { code: 'R2', name: '稳健型' };
    if (score === 4) return { code: 'R3', name: '平衡型' };
    if (score === 5) return { code: 'R4', name: '进取型' };
    return { code: 'R5', name: '激进型' };
});

const fetchAccount = async () => {
    if (!user.value?.id) return;
    accountLoading.value = true;
    try {
        const response = await getAccountByUserId(user.value.id);
        account.value = response.data;
    } catch (error) {
        if (error.response?.status !== 404) {
            ElMessage.error("获取账户信息失败: " + (error.response?.data?.message || error.message));
        }
        account.value = null;
    } finally {
        accountLoading.value = false;
    }
};

const openCreateDialog = () => {
    form.userId = user.value.id;
    createDialogVisible.value = true;
};

const resetForm = () => {
    activeStep.value = 0;
    kycForm.q1 = null;
    kycForm.q2 = null;
    form.balance = 100000.00;
    form.riskLevel = null;
};

const prevStep = () => {
    if (activeStep.value > 0) activeStep.value--;
};

const nextStep = () => {
    if (activeStep.value === 0) {
        if (!kycForm.q1 || !kycForm.q2) {
            ElMessage.warning('请完成所有评估问题');
            return;
        }
    }
    if (activeStep.value < 2) activeStep.value++;
};

const handleCreate = async () => {
    submitting.value = true;
    try {
        form.riskLevel = determinedRiskLevel.value.code;
        await createAccount(form);
        ElMessage.success('账户开通成功！');
        createDialogVisible.value = false;
        await fetchAccount();
    } catch (error) {
        if (error.response?.status === 409) {
            ElMessage.error('开通失败：您已拥有账户，请勿重复创建。');
        } else {
            ElMessage.error('开通失败: ' + (error.response?.data?.message || error.message));
        }
    } finally {
        submitting.value = false;
    }
};

onMounted(fetchAccount);
</script>

<style scoped>
.home-container {
    padding: 20px;
}

.mt-4 {
    margin-top: 1.5rem;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 18px;
    font-weight: bold;
}

.holdings-section {
    margin-top: 24px;
}

.holdings-title {
    font-size: 16px;
    margin-bottom: 12px;
    color: #303133;
}

.account-placeholder {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 200px;
}

.el-form-item--top .el-form-item__label {
    padding-bottom: 0;
    font-weight: 500;
}
</style>